package com.rslai.base.tool.servertest.command;

import com.rslai.base.tool.servertest.context.Context;
import com.rslai.base.tool.servertest.response.Response;
import com.rslai.base.tool.servertest.util.PropertyUtils;

import java.util.Collections;
import java.util.Map;

import org.slf4j.Logger;

public class CoberturaCommand extends StepCommand {
    private String caseId;

    public CoberturaCommand(String caseId) {
        this.caseId = caseId;
    }

    public Response doExecute(Response param, Context context) throws Throwable {
        String cobertura = getCobertura();
        if (Boolean.parseBoolean(cobertura)) {
            this.logger.info("collect {} cobertura", this.caseId);
            Process proc = Runtime.getRuntime().exec(String.format("bash /home/q/tools/devbin/cobertools/cobertura_collect_onecase.sh %s", new Object[]{this.caseId}));
            waitExec(proc);
        }
        return null;
    }

    private String getCobertura() {
        String cobertura = System.getProperty("cobertura");
        return cobertura == null ? PropertyUtils.getProperty("cobertura") : cobertura;
    }

    private void waitExec(Process proc) {
        try {
            proc.waitFor();
        } catch (Exception e) {
            this.logger.error("Execute shell error", e);
        } finally {
            proc.destroy();
        }
    }

    protected StepCommand doClone() {
        return new CoberturaCommand(this.caseId);
    }

    public Map<String, Object> toReport() {
        return Collections.emptyMap();
    }
}
